'use strict';

const http = require('http'),
    fs=require('fs'),
    config=require('./config.js'),
    util=require('./util.js'),
    httpHandler=require('./httpHandler.js'),
    userData={};    //存储用户数据，key为socket id

//先定义HTTP服务器，因为socket.io依赖它
const server = http.createServer(httpHandler).listen(3003);

//定义socket.io，并“捆绑”在HTTP服务器
const io = require('socket.io').listen(server);

//此处io等于io.socket
io.on('connection', function(socket){
    //socket.broadcast.emit('hi');

    socket.on('newUser', function(data){
        //当有新的连接过来时
        console.log("Connection " + socket.id +'['+data.userName + "] accepted.");

        userData[socket.id]=data;

        refreshUserList();
    });

    //为这个socket监听一些事件，注意此事件名可以自定义，纯粹作为一个服务端与客户端的标识符
    socket.on('message', function(message){
        //服务端发送消息回客户端
        io.emit('message', {
            sender:userData[socket.id].userName,
            msg:message
        });
    });

    socket.on('disconnect', function(){
        var data=userData[socket.id];
        if(data) {
            console.log("Connection " + socket.id + '[' + data.userName + "] terminated.");

            //删除相关数据
            delete userData[socket.id];
        }

        refreshUserList();
    });
});

//刷新用户列表
function refreshUserList(){
    var userList=[];
    for(var id in userData){
        userList.push(userData[id].userName);
    }

    io.emit('userList', {userList:userList});
}